<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Model;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Writer_Excel5;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Fill;
use PHPExcel_Style_Border;
use PHPExcel_Cell_DataType;

//人员管理模块
class Employees extends Common
{
    //导入员工
    public function newdru(){
        return $this->fetch();
    }
    //选择网点列表
    public function selectnet($netids='')
    {
        //echo $jxsids;
        $jarr=[];
        if($netids){
            $jarr=explode(',',$netids);
        }
       // print_r($jarr);
        $jxs= db("cg_jxs")->field("title as name,id")->select();
        $sys=[];
        for($i=0;$i<count($jxs);$i++){
            $tmp=db("cg_system")->where("jxs={$jxs[$i]["id"]}")->field("title as name,id,jxs as pid")->select();
            
            for($j=0;$j<count($tmp);$j++){
                $net=db("cg_net")->where("system_id={$tmp[$j]["id"]}")->field("title as name,id,system_id as pid")->select();
                for($k=0;$k<count($net);$k++){
                    if(in_array($net[$k]["id"],$jarr)){
                        $net[$k]["checked"]='true';
                    }else{
                        $net[$k]["checked"]='false';
                    }
                    $sys[]=$net[$k];
                }
                $sys[]=$tmp[$j];
            }
           
            $sys[]=$jxs[$i];
        }
        $sys=json_encode($sys);
        $this->assign("sys",$sys);
        return $this->fetch();
    }
    //查询所有网点
    public function netjson(){
        $data = Db::table('cg_net')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    //选择系统列表
    public function selectsys($sysids='')
    {
        //echo $jxsids;
        $jarr=[];
        if($sysids){
            $jarr=explode(',',$sysids);
        }
       // print_r($jarr);
        $jxs= db("cg_jxs")->field("title as name,id")->select();
        $sys=[];
        for($i=0;$i<count($jxs);$i++){
            $tmp=db("cg_system")->where("jxs={$jxs[$i]["id"]}")->field("title as name,id,jxs as pid")->select();
            $flag=0;
            for($j=0;$j<count($tmp);$j++){
                if(in_array($tmp[$j]["id"],$jarr)){
                    $tmp[$j]["checked"]='true';$flag=1;
                }else{
                    $tmp[$j]["checked"]='false';$flag=0;
                }
                $sys[]=$tmp[$j];
            }
           
            $sys[]=$jxs[$i];
        }
        $sys=json_encode($sys);
        $this->assign("sys",$sys);
        return $this->fetch();
    }
   //查询所有系统
    public function sysjson(){
        $data = Db::table('cg_system')->field('title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    //选择经销商列表
    public function selectjxs($jxsids='')
    {
        //echo $jxsids;
        $jarr=[];
        if($jxsids){
            $jarr=explode(',',$jxsids);
        }
       // print_r($jarr);
        $jxs= db("cg_jxs")->field("title as name,id")->select();
        for($i=0;$i<count($jxs);$i++){
            if(in_array($jxs[$i]["id"], $jarr)){
                $jxs[$i]["checked"]='true';
            }else{
                $jxs[$i]["checked"]='false';
            }
        }
        $jxs=json_encode($jxs);
        $this->assign("jxs",$jxs);
        return $this->fetch();
    }
//查询所有经销商
    public function jxsjson(){
        $jxs_id = $this->request->param('jxs_id');
        $where = [];
        if($jxs_id){
            $where['id'] = $jxs_id;
        }
        //查询所有省份
        $data = Db::table('cg_jxs')->field('title,id')->where($where)->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    public function dcw(){
        $where = "e.is_actived=1 and e.is_deleted=0 ";
        $user=db("employee e")->join("department_employee de","e.id=de.employee_id","LEFT")
        ->join("department d","de.department_id=d.id","LEFT")
        ->join("users u","e.id=u.employee_id","LEFT")
        ->join("users_role ur","u.id=ur.users_id","LEFT")
        ->join("role r","ur.role_id=r.id","LEFT")
        ->join("users_role_group urg","u.id=urg.users_id","LEFT")
        ->join("role_group rg","urg.role_group_id=rg.id","LEFT")
        ->join("job_employee je","e.id=je.employee_id","LEFT")
        ->join("job j","je.job_id=j.id","LEFT")
        ->order("e.id")
        ->distinct("e.id")
        ->field("e.id")
        ->select();
        $res_Arr=[];
        foreach ($user as $k => $v) {
            $res_Arr[]=$v["id"];
        }
        $eids=implode(',',$res_Arr);
        $emp_model = model('Employee');
        if($eids){
            $emp=$emp_model->get_employ($eids);
        }else{
            $emp=[];
        }
        for($i=0;$i<count($emp);$i++){
            $state=db("employee")->where("id={$emp[$i]["id"]}")->value("state");
            if($state==1){
                $emp[$i]["state"]="在职";
            }else if($state==2){
                $emp[$i]["state"]="试用";
            }else{
                $emp[$i]["state"]="离职";
            }
            $emp[$i]["job"]=db("job_employee je")->join("job j","je.job_id=j.id")->where("je.employee_id={$emp[$i]["id"]}")->value("j.job_name");
            //其他部门
            $tmpbumen=db("department_employee de")->join("department d","de.department_id=d.id")->where("de.employee_id={$emp[$i]["id"]} and de.index>1")->field("d.de_name")->select();
            if($tmpbumen){
                $tmpb=[];
                foreach ($tmpbumen as $k => $v) {
                    # code...
                    $tmpb[]=$v["de_name"];
                }
                $emp[$i]["obumen"]=implode(',',$tmpb);
            }else{
                $emp[$i]["obumen"]="";
            }
            if($emp[$i]["uid"])
                $emp[$i]["role"]=db("users_role ur")->join("role r","ur.role_id=r.id")->where("ur.users_id={$emp[$i]["uid"]}")->value("r.role_name");
            else
                $emp[$i]["role"]="";
            //角色组
            if($emp[$i]["uid"]){
                $tmprg=db("users_role_group ug")->join("role_group rg","ug.role_group_id=rg.id")->where("ug.users_id={$emp[$i]["uid"]}")->field("group_name")->select();
                if($tmprg){
                    $rg=[];
                    foreach ($tmprg as $k => $v) {
                        # code...
                        $rg[]=$v["group_name"];
                    }
                    $emp[$i]["rg"]=implode(',',$rg);
                }else{
                   $emp[$i]["rg"]=""; 
                }
            }else
                $emp[$i]["rg"]="";
        }
       // print_r($emp);
       $eid = Session::get("employee_id");
        $users = Db::table("employee")->where(["id" => $eid])->find();

        Vendor("PHPExcel");


        Vendor("PHPExcel.Writer.Excel5");

        // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new PHPExcel();


        $objProps = $objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setTitle("人员列表");

        #################总标题

        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:K1');
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "人员列表");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14);
        #################表头信息
        $objPHPExcel->getActiveSheet()->mergeCells('A2:K2');
        $objPHPExcel->getActiveSheet()->setCellValue('A2', "(本表单由软件导出，导出时间：" . date("Y-m-d H:i:s") . "；导出人：{$users["em_name"]})");
        //水平剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        //垂直剧中
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        //加粗
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
        //字体
        $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(12);
        $objPHPExcel->getActiveSheet()->getStyle('3')->getAlignment()->setWrapText(true);
        
         $objPHPExcel->getActiveSheet()->getStyle('A3:K3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
         $objPHPExcel->getActiveSheet()->getStyle('A3:K3')->getFill()->getStartColor()->setARGB('0099CCFF');
             //水平剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:K3')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
         $objPHPExcel->getActiveSheet()->getStyle('A3:K3')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $objPHPExcel->getActiveSheet()->setCellValue('A3',"序号");
        $objPHPExcel->getActiveSheet()->setCellValue('B3',"姓名");
        $objPHPExcel->getActiveSheet()->setCellValue('C3',"用户名");
        $objPHPExcel->getActiveSheet()->setCellValue('D3',"所属部门");
        $objPHPExcel->getActiveSheet()->setCellValue('E3',"岗位名称");
        $objPHPExcel->getActiveSheet()->setCellValue('F3',"其他部门");
        $objPHPExcel->getActiveSheet()->setCellValue('G3',"身份证号");
        $objPHPExcel->getActiveSheet()->setCellValue('H3',"手机号码");
        $objPHPExcel->getActiveSheet()->setCellValue('I3',"角色");
        $objPHPExcel->getActiveSheet()->setCellValue('J3',"角色分组");
        $objPHPExcel->getActiveSheet()->setCellValue('K3',"状态");
         $h=3;
        for($i=0;$i<count($emp);$i++){
            $h++;
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$h,$i+1,PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('B'.$h,$emp[$i]["em_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('C'.$h,$emp[$i]["login_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('D'.$h,$emp[$i]["de_name"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('E'.$h,$emp[$i]["job"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('F'.$h,$emp[$i]["obumen"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('G'.$h,$emp[$i]["idcard"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('H'.$h,$emp[$i]["mobile"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('I'.$h,$emp[$i]["role"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('J'.$h,$emp[$i]["rg"],PHPExcel_Cell_DataType::TYPE_STRING);
            $objPHPExcel->getActiveSheet()->setCellValueExplicit('K'.$h,$emp[$i]["state"],PHPExcel_Cell_DataType::TYPE_STRING);
        }
         $styleArray = array(  
        'borders' => array(  
            'allborders' => array(  
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                //'color' => array('argb' => 'FFFF0000'),  
            ),  
        ),  
    );  
            $objPHPExcel->getActiveSheet()->getStyle('A1:K'.$h)->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪
        //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
           $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        //var_dump($objWriter);exit;
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=file.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
    public function manage($page = 1, $list = 10)
    {
        //$arr=$this->my_own_jxs();
        //print_r($arr);
        $where = "d.is_actived=1 and d.is_deleted=0 ";
        //树状图数据
        $alldepart = Db::table("department")->alias("d")->where($where)->order("index")->field("id,parent_id as pId,de_name as name")->select();
        $this->assign("alldepart", json_encode($alldepart));


        //接收数据
        $request = Request::instance();


        $data = $request->post();
        $where = "e.is_actived=1 and e.is_deleted=0 ";
        if ($data) {
            if (trim($data["em_name"])) {
                $em_name = trim($data["em_name"]);
                $where .= "and e.em_name='{$em_name}' ";
            }
            if (trim($data["de_name"])) {
                //查询用户所查询部门的数据情况
                $this_depart = Db::table("department")->where(["de_name" => trim($data["de_name"]), "is_actived" => 1, "is_deleted" => 0])->find();
                if ($this_depart) {
                    if ($data["check_type"]) {
                        switch ($data["check_type"]) {
                            case '2':
                                # code...本部门
                                $where .= "and d.id={$this_depart['id']} and de.index=1 ";
                                break;
                            case '3':
                                # code...下属
                                $where .= "and d.path like '%[{$this_depart['id']}]%' and de.index=1 ";
                                break;
                            default:
                                # code...本部门及下属
                                $data["check_type"] = 1;
                                $where .= "and (d.path like '%[{$this_depart['id']}]%' or d.id={$this_depart['id']}) and de.index=1 ";
                                break;
                        }
                    } else {
                        # code...本部门及下属
                        $data["check_type"] = 1;
                        $where .= "and (d.path like '%[{$this_depart['id']}]%' or d.id={$this_depart['id']}) and de.index=1 ";
                    }
                } else {
                    $where .= "and d.id=-1 ";
                }


            }//部门搜索结束
            if (trim($data["login_name"])) {
                $lname = trim($data["login_name"]);
                $where .= "and u.login_name='{$lname}' ";
            }//帐号搜索
            if (trim($data["id_card"])) {
                $ic = trim($data["id_card"]);
                $where .= "and e.idcard='{$ic}' ";
            }//身份证号
            if (trim($data["mobile"])) {
                $mobile = trim($data["mobile"]);
                $where .= "and e.mobile='{$mobile}' ";
            }//手机号
            if (trim($data["is_login"])) {
                switch (trim($data["is_login"])) {
                    case '2':
                        # code...已开通
                        $where .= "and u.id is not null ";
                        break;
                    case '3':
                        $where .= "and u.id is null ";
                        # code...未开通
                        break;
                    default:
                        # code...全部
                        $data["is_login"] = 1;
                        break;
                }
            }
            //is_login是否拥有帐号

            //1在职  2试用  3离职
            if (trim($data["state"])) {
                $st = trim($data["state"]);
                switch (trim($data["state"])) {
                    case '1':

                    case '2':

                    case '3':
                        $where .= "and e.state={$st} ";
                        break;
                    default:
                        # code...
                        $data["state"] = 0;
                        break;
                }
            }//状态
            //role角色
            if (trim($data["role"])) {
                $role = trim($data["role"]);
                $where .= "and r.role_name='{$role}' ";
            }
            //role角色组
            if (trim($data["role_group"])) {
                $role_group = trim($data["role_group"]);
                $where .= "and rg.group_name='{$role_group}' ";
            }
            //job_name
            if (trim($data["job_name"])) {
                $job_name = trim($data["job_name"]);
                $where .= "and j.job_name='{$job_name}' ";
            }
        } else {
            //默认显示数据
            $data = [
                "em_name" => "", "de_name" => "",
                "check_type" => 1, "login_name" => "",
                "id_card" => "", "mobile" => "",
                "is_login" => 1, "state" => 0, "role" => "", "role_group" => "", "job_name" => ""
            ];
        }


        //echo $where;

        $page = $page > 1 ? $page : 1;
        $sum = 0;
        $emp_model = model('Employee');
        //echo $where;
        $sum = $emp_model->get_employ_count($where);
        $maxpage = ceil($sum / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        //echo $emp_model->getLastSql();
        //获取数据
        $em_list = [];//员工列表
        $other_depart = [];//其余部门
        $role_arr = [];//角色
        $role_group_arr = [];//角色组
        $job_list = [];//岗位
        if ($sum) {
            //数量大于0才查询
            $eid_arr = $emp_model->get_eid_list($where, $page, $list);
            $eids = implode(',', $eid_arr);
            //echo $eids;
            //获取员工列表
            $em_list = $emp_model->get_employ($eids);
            //获取其他部门
            $other_depart = Db::table("department_employee")->alias("de")->join("department d", "de.department_id=d.id")
                ->where("d.is_actived=1 and d.is_deleted=0 and de.index<>1 and de.employee_id in ({$eids})")
                ->field("de.employee_id as em_id,d.id as de_id,d.de_name")
                ->select();
            //获取角色列表
            $role_arr = $emp_model->get_role_arr($eids);
            //获取角色组列表
            $role_group_arr = $emp_model->get_role_group_arr($eids);
            //获取岗位
            $job_list = $emp_model->get_job_list($eids);

        }


        $this->assign("em_list", $em_list);
        $this->assign("job_list", $job_list);
        $this->assign("other_depart", $other_depart);
        $this->assign("role_arr", $role_arr);
        $this->assign("role_group_arr", $role_group_arr);
        $this->assign("data", $data);
        $this->assign("sum", $sum);
        $this->assign("maxpage", $maxpage);
        $this->assign("page", $page);
        $this->assign("list", $list);
        return $this->fetch('manage');
    }

    public function newem($emid = 0)
    {


        if ($emid) {
            //获取人员基本信息
            $data = Db::table("employee")->alias("e")
                ->join("department_employee de", "e.id=de.employee_id", "LEFT")
                ->join("department d", "de.department_id=d.id", "LEFT")
                ->join("job_employee je", "e.id=je.employee_id", "LEFT")
                ->join("job j", "je.job_id=j.id", "LEFT")
                ->join("users u", "e.id=u.employee_id", "LEFT")
                ->join("users_role ur", "u.id=ur.users_id", "LEFT")
                ->join("role r", "ur.role_id=r.id", "LEFT")
                ->join("users_role_group urg", "u.id=urg.users_id", "LEFT")
                ->join("role_group rg", "urg.role_group_id=rg.id", "LEFT")
                ->where("e.id={$emid} and (de.index=1 or de.index is null) and e.is_actived=1 and e.is_deleted=0")
                ->field("e.em_no,e.state,e.em_name,e.mobile,e.WeChat,e.email,e.idcard,e.entry,e.gender,d.id as de_id,d.de_name,d.principal,j.job_name,j.id as job_id,u.login_name,u.type as utype,u.state as ustate,u.is_SFA,u.power,u.id as login_id,rg.id as rgid,rg.group_name,r.id as rid,r.role_name,u.jxs_ids,u.sys_ids,u.net_ids")->find();
            //print_r($data);
            if (!$data) {
                return $this->redirect("Employees/manage");
            }
            if (!$data["ustate"])
                $data["ustate"] = 1;
            $dataodepart = Db::table("department_employee")->alias("de")->join("department d", "de.department_id=d.id")
                ->where("de.employee_id={$emid} and de.index<>1 and d.is_actived=1 and d.is_deleted=0")->field("d.id,d.de_name")->select();
        } else {
            $data = ["em_no" => "", "state" => 1, "em_name" => "", "mobile" => "", "WeChat" => "", "email" => "", "idcard" => "", "entry" => "", "gender" => 1,
                "de_id" => "", "de_name" => "", "principal" => "-2", "job_name" => "", "job_id" => "", "login_name" => "", "utype" => 1, "ustate" => 1,
                "is_SFA" => 0, "power" => 1, "login_id" => "", "rgid" => "", "group_name" => "", "rid" => "", "role_name" => "","jxs_ids"=>"","sys_ids"=>"","net_ids"=>""
            ];//暂无帐号信息以后添加
            $dataodepart = [];
        }
        $jxss=[];
        if($data["jxs_ids"]){
            $jxss=db("cg_jxs")->where("id in ({$data["jxs_ids"]})")->field("id,title")->select();
        }
        $this->assign("jxss",$jxss);
        $syss=[];
        if($data["sys_ids"]){
            $syss=db("cg_system")->where("id in ({$data["sys_ids"]})")->field("id,title")->select();
        }
        $this->assign("syss",$syss);
        $nets=[];
        if($data["net_ids"]){
            $nets=db("cg_net")->where("id in ({$data["net_ids"]})")->field("id,title")->select();
        }

        $this->assign("nets",$nets);
        $this->assign("data", $data);
        $this->assign("dataodepart", $dataodepart);
        $this->assign("emid", $emid);
        return $this->fetch('newem');
    }

    //获取所有岗位
    public function getjobs()
    {
        $arr = Db::table("job")->where(["is_actived" => 1, "is_deleted" => 0])
            ->field("id,job_name as name,parent_id as pId")->select();
        return json_encode($arr);
    }

    //修改角色
    public function update_role()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        if ($data) {
            $newdata["id"] = $data["role_id"];
            $newdata["role_name"] = htmlspecialchars(trim($data["role_name"]));
            if (trim($data["parent_id"]))
                $newdata["parent_id"] = trim($data["parent_id"]);
            else
                $newdata["parent_id"] = null;
            $newdata["remark"] = htmlspecialchars(trim($data["remark"]));
            $newdata["modifiled_on"] = date("Y-m-d H:i:s");
            //处理path
            $newdata["path"] = null;
            if ($newdata["parent_id"]) {
                //查询上级的path
                $pjob = Db::table("role")->where("id={$newdata["parent_id"]}")->find();
                $newdata["path"] = $pjob["path"] . "[{$newdata["parent_id"]}]";
            }
            if (!$newdata["role_name"])
                return 2;
            //判断重复
            $ischongfu = Db::table("role")->where("role_name='{$newdata["role_name"]}' and id<>{$newdata["id"]}")->count();

            if ($ischongfu)
                return 4;

            //获取自身原先path
            $yuan = Db::table("role")->where("id={$newdata["id"]}")->find();
            $oldpath = $yuan["path"];
            //开始修改
            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("role")->update($newdata);
                //替换所有下级的path
                $xiaji = Db::table("role")->where("path like '%[{$newdata["id"]}]%'")->select();
                $check = 0;
                for ($i = 0; $i < count($xiaji); $i++) {
                    if ($oldpath) {
                        $tmparr["path"] = str_replace($oldpath, $newdata["path"], $xiaji[$i]["path"]);
                    } else {
                        $tmparr["path"] = $newdata["path"] . $xiaji[$i]["path"];
                    }

                    $tmparr["modifiled_on"] = date("Y-m-d H:i:s");
                    $tmparr["id"] = $xiaji[$i]["id"];
                    $tmpres = Db::table("role")->update($tmparr);
                    if ($tmpres)
                        $check++;

                }
                if ($check == count($xiaji))
                    $res2 = 1;
                else
                    $res2 = 0;


            } catch (\Exception $e) {
                Db::rollBack();
                return 31;//失败
            }
            if ($res1 && $res2) {
                Db::commit(); //事物提交
                return 1;//成功
            } else {
                Db::rollBack();
                return 32;//失败
            }
        } else {
            return 0;
        }
        // return 1;
    }

    //新建角色
    public function new_role()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        if ($data) {
            $newdata["role_name"] = htmlspecialchars(trim($data["role_name"]));
            $newdata["parent_id"] = trim($data["parent_id"]);
            $newdata["remark"] = htmlspecialchars(trim($data["remark"]));
            $newdata["created_on"] = date("Y-m-d H:i:s");
            //处理path
            $newdata["path"] = "";
            if ($newdata["parent_id"]) {
                //查询上级的path
                $pjob = Db::table("role")->where("id={$newdata["parent_id"]}")->find();
                $newdata["path"] = $pjob["path"] . "[{$newdata["parent_id"]}]";
            }
            if (!$newdata["role_name"])
                return 2;
            //判断重复
            $ischongfu = Db::table("role")->where("role_name='{$newdata["role_name"]}'")->count();

            if ($ischongfu)
                return 4;

            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("role")->insert($newdata);
            } catch (\Exception $e) {
                Db::rollBack();
                return 3;//失败
            }
            if ($res1) {
                Db::commit(); //事物提交
                return 1;//成功
            } else {
                Db::rollBack();
                return 3;//失败
            }
        } else {
            return 0;
        }
    }

    //创建职位
    public function new_job()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        //print_r($data);exit;
        if ($data) {
            $newdata["job_no"] = trim($data["job_no"]);
            $newdata["job_name"] = htmlspecialchars(trim($data["job_name"]));
            $newdata["parent_id"] = trim($data["parent_id"]);
            $newdata["job_title"] = htmlspecialchars(trim($data["job_title"]));
            $newdata["job_level"] = trim($data["job_level"]);
            $newdata["department_id"] = trim($data["department_id"]);
            $newdata["remark"] = htmlspecialchars(trim($data["remark"]));
            $newdata["created_on"] = date("Y-m-d H:i:s");
            //处理path
            $newdata["path"] = "";
            if ($newdata["parent_id"]) {
                //查询上级的path
                $pjob = Db::table("job")->where("id={$newdata["parent_id"]}")->find();
                $newdata["path"] = $pjob["path"] . "[{$newdata["parent_id"]}]";
            }
            if (!$newdata["job_no"])
                return 2;//岗位编号空
            if (!$newdata["job_name"])
                return 3;//岗位名空
            if (!$newdata["job_title"])
                return 4;//岗位称谓空
            if (!$newdata["job_level"])
                return 5;//等级空
            if (!$newdata["department_id"])
                return 6;//部门空
            $is_chongfu = Db::table("job")->where("job_name='{$newdata["job_name"]}' or job_no='{$newdata["job_no"]}'")->count();
            if ($is_chongfu)
                return 8;//重现重复


            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("job")->insert($newdata);
            } catch (\Exception $e) {
                Db::rollBack();
                return 7;//失败
            }
            if ($res1) {
                Db::commit(); //事物提交
                return 1;//成功
            } else {
                Db::rollBack();
                return 7;//失败
            }
        } else {
            return 0;
        }
    }

    //获取无分层岗位
    public function get_no_tree($deid = 0)
    {
        $where["is_actived"] = 1;
        $where["is_deleted"] = 0;

        if ($deid) {
            $where["department_id"] = $deid;
        }
        $arr = Db::table("job")->where($where)->field("id,job_name as name")->select();
        return json_encode($arr);
    }

    //创建员工和用户
    public function new_employee_user()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        //判断员工编号是否存在
        $iscf = Db::table("employee")->where(["em_no" => trim($data["em_no"])])->count();
        
        if ($iscf) {
            return 2;//工号重复
        } else {

            $iszhchongfu = Db::table("users")->where("login_name='{$data["login_name"]}'")->find();
            if ($iszhchongfu)
                return 9;
            //接收和处理数据
            $addData["created_on"] = date("Y-m-d H:i:s");
            $addData["em_no"] = htmlspecialchars(trim($data["em_no"]));
            $addData["em_name"] = htmlspecialchars(trim($data["em_name"]));
            $addData["state"] = trim($data["state"]);
            $addData["mobile"] = htmlspecialchars(trim($data["mobile"]));
            $addData["WeChat"] = htmlspecialchars(trim($data["wechart"]));
            $addData["email"] = htmlspecialchars(trim($data["email"]));
            $addData["idcard"] = htmlspecialchars(trim($data["idcard"]));
            $addData["gender"] = trim($data["gender"]);
            if ($data["entry"]) {
                $addData["entry"] = trim($data["entry"]);
            }


            //print_r($addData);exit;
            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("employee")->insertGetId($addData);
                $userId = $res1;
                //echo $userId;
                //插入部门
                //主部门

                $datae_d[0]["employee_id"] = $userId;
                $datae_d[0]["department_id"] = htmlspecialchars(trim($data["de_id"]));
                $datae_d[0]["index"] = 1;
                //其他部门
                $odearr = trim($data["otherdepart"]);
                if ($odearr) {
                    $odearr = explode(",", $odearr);
                    for ($i = 0; $i < count($odearr); $i++) {
                        $datae_d[$i + 1]["employee_id"] = $userId;
                        $datae_d[$i + 1]["department_id"] = $odearr[$i];
                        $datae_d[$i + 1]["index"] = 2;
                    }
                }

                $res2 = Db::table("department_employee")->insertAll($datae_d);

                //插入岗位
                $datae_j["employee_id"] = $userId;
                $datae_j["job_id"] = htmlspecialchars(trim($data["job_id"]));

                $res3 = Db::table("job_employee")->insert($datae_j);

                //判断是否需要修改部门的第一负责人
                $res4 = "";
                if ($data["is_main"] == 1) {
                    $dechage["principal"] = $userId;
                    $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                    $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                    $res4 = Db::table("department")->update($dechage);


                } else {
                    $res4 = 1;
                }
                /*帐号特有信息
                                  login_name:$("#login_name").val(),
                                  login_pwd:$("#login_pwd").val(),
                                  user_type:$("input[name='user_type']:checked").val(),
                                  user_state:$("input[name='user_state']:checked").val(),
                                  user_is_SFA:$("input[name='user_is_SFA']:checked").val(),
                                  user_power:$("input[name='user_power']:checked").val(),
                                  role_id:$("#role_id").val(),
                                  roleg_id:$("#roleg_id").val()
               */
                //插入帐号表
                
                $userdata["login_name"] = htmlspecialchars(trim($data["login_name"]));
                $userdata["login_pwd"] = md5(md5(htmlspecialchars(trim($data["login_pwd"]))));
                $userdata["type"] = trim($data["user_type"]);
                $userdata["state"] = trim($data["user_state"]);
                $userdata["is_SFA"] = trim($data["user_is_SFA"]);
                $userdata["power"] = trim($data["user_power"]);
                $userdata["employee_id"] = $userId;
                $userdata["created_on"] = date("Y-m-d H:i:s");
                $userdata["jxs_ids"] = trim($data["jxs_ids"]);
                $userdata["sys_ids"] = trim($data["sys_ids"]);
                $userdata["net_ids"] = trim($data["net_ids"]);
                $res5 = Db::table("users")->insertGetId($userdata);

                //同时增加微信通讯录
                $wx = [];
                $wx['zh'] = $userdata['login_name'];
                $wx['xm'] = $addData["em_name"];
                $wx['wxh'] = $addData["WeChat"];
                $wx['bm'] = 1;
                $wx['zw'] = db('job')->where('id',$datae_j["job_id"])->value('job_name');
                $wx['sj'] = $addData["mobile"];
                $wx['yx'] = $addData["email"];
                db('cg_wechat')->insert($wx);

                //插入帐号——角色

                $dataur["users_id"] = $res5;
                $dataur["role_id"] = trim($data["role_id"]);
                $res6 = Db::table("users_role")->insert($dataur);


                //插入帐号角色组表
                if (trim($data["roleg_id"])) {
                    $dataurg["users_id"] = $res5;
                    $dataurg["role_group_id"] = trim($data["roleg_id"]);
                    $res7 = Db::table("users_role_group")->insert($dataurg);
                } else {
                    $res7 = 1;
                }

            } catch (\Exception $e) {

                Db::rollBack();
                return $e->getMessage();//失败

            }
            if ($res1 && $res2 && $res3 && $res4 && $res5 && $res6 && $res7) {

                Db::commit(); //事物提交
                return 1;
            } else {

                Db::rollBack();
                return 3;//失败
            }
        }
    }

    //只创建员工不创建用户
    public function new_employee()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        //判断员工编号是否存在
        $iscf = Db::table("employee")->where(["em_no" => trim($data["em_no"])])->count();
        if ($iscf) {
            return 2;//工号重复
        } else {
            //接收和处理数据
            $addData["created_on"] = date("Y-m-d H:i:s");
            $addData["em_no"] = htmlspecialchars(trim($data["em_no"]));
            $addData["em_name"] = htmlspecialchars(trim($data["em_name"]));
            $addData["state"] = trim($data["state"]);
            $addData["mobile"] = htmlspecialchars(trim($data["mobile"]));
            $addData["WeChat"] = htmlspecialchars(trim($data["wechart"]));
            $addData["email"] = htmlspecialchars(trim($data["email"]));
            $addData["idcard"] = htmlspecialchars(trim($data["idcard"]));
            $addData["gender"] = trim($data["gender"]);
            if ($data["entry"]) {
                $addData["entry"] = trim($data["entry"]);
            }


            //print_r($addData);exit;
            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("employee")->insertGetId($addData);
                $userId = $res1;
                //echo $userId;
                //插入部门
                //主部门

                $datae_d[0]["employee_id"] = $userId;
                $datae_d[0]["department_id"] = htmlspecialchars(trim($data["de_id"]));
                $datae_d[0]["index"] = 1;
                //其他部门
                $odearr = trim($data["otherdepart"]);
                if ($odearr) {
                    $odearr = explode(",", $odearr);
                    for ($i = 0; $i < count($odearr); $i++) {
                        $datae_d[$i + 1]["employee_id"] = $userId;
                        $datae_d[$i + 1]["department_id"] = $odearr[$i];
                        $datae_d[$i + 1]["index"] = 2;
                    }
                }

                $res2 = Db::table("department_employee")->insertAll($datae_d);

                //插入岗位
                $datae_j["employee_id"] = $userId;
                $datae_j["job_id"] = htmlspecialchars(trim($data["job_id"]));

                $res3 = Db::table("job_employee")->insert($datae_j);

                //判断是否需要修改部门的第一负责人
                $res4 = "";
                if ($data["is_main"] == 1) {
                    $dechage["principal"] = $userId;
                    $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                    $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                    $res4 = Db::table("department")->update($dechage);
                } else {
                    $res4 = 1;
                }
            } catch (\Exception $e) {

                Db::rollBack();
                return 3;//失败

            }
            if ($res1 && $res2 && $res3 && $res4) {

                Db::commit(); //事物提交
                return 1;
            } else {

                Db::rollBack();
                return 3;//失败
            }
        }
    }

    //修改有帐号
    public function update_employee_user()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        //接收和处理数据
        $upData["id"] = $data["emid"];
        $upData["em_no"] = htmlspecialchars(trim($data["em_no"]));
        $upData["em_name"] = htmlspecialchars(trim($data["em_name"]));
        $upData["state"] = trim($data["state"]);
        $upData["mobile"] = htmlspecialchars(trim($data["mobile"]));
        $upData["WeChat"] = htmlspecialchars(trim($data["wechart"]));
        $upData["email"] = htmlspecialchars(trim($data["email"]));
        $upData["idcard"] = htmlspecialchars(trim($data["idcard"]));
        $upData["gender"] = trim($data["gender"]);
        $upData["modifiled_on"] = date("Y-m-d H:i:s");
        if ($data["entry"]) {
            $upData["entry"] = trim($data["entry"]);
        }
        Db::startTrans(); //开启事物
        try {
            $res1 = Db::table("employee")->update($upData);
            //部门处理
            //
            Db::table("department_employee")->where("employee_id={$data["emid"]}")->delete();
            $datae_d[0]["employee_id"] = $data["emid"];
            $datae_d[0]["department_id"] = htmlspecialchars(trim($data["de_id"]));
            $datae_d[0]["index"] = 1;
            //其他部门
            $odearr = trim($data["otherdepart"]);
            if ($odearr) {
                $odearr = explode(",", $odearr);
                for ($i = 0; $i < count($odearr); $i++) {
                    $datae_d[$i + 1]["employee_id"] = $data["emid"];
                    $datae_d[$i + 1]["department_id"] = $odearr[$i];
                    $datae_d[$i + 1]["index"] = 2;
                }
            }
            $res2 = Db::table("department_employee")->insertAll($datae_d);
            //岗位处理
            Db::table("job_employee")->where("employee_id={$data["emid"]}")->delete();
            $datae_j["employee_id"] = $data["emid"];
            $datae_j["job_id"] = htmlspecialchars(trim($data["job_id"]));

            $res3 = Db::table("job_employee")->insert($datae_j);
            //判断是否需要修改部门的第一负责人
            $depa = Db::table("department")->where("id={$data["de_id"]}")->find();
            $principalid = $depa["principal"];
            $res4 = "";
            if ($data["is_main"] == 1) {
                $dechage["principal"] = $data["emid"];
                $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                $res4 = Db::table("department")->update($dechage);
            } else {
                if ($principalid == $data["emid"]) {
                    $dechage["principal"] = null;
                    $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                    $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                    $res4 = Db::table("department")->update($dechage);
                } else {
                    $res4 = 1;
                }
            }
           
            //判断帐号是否存在
            if (trim($data["login_id"])) {
                //有帐号修改
                $uid = trim($data["login_id"]);
                $userdata["id"] = $uid;
                $userdata["type"] = trim($data["user_type"]);
                $userdata["state"] = trim($data["user_state"]);
                $userdata["is_SFA"] = trim($data["user_is_SFA"]);
                $userdata["power"] = trim($data["user_power"]);
                 $userdata["jxs_ids"] = trim($data["jxs_ids"]);
                $userdata["sys_ids"] = trim($data["sys_ids"]);
                $userdata["net_ids"] = trim($data["net_ids"]);
                $userdata["modifiled_on"] = date("Y-m-d H:i:s");
                $res5 = Db::table("users")->update($userdata);


                //清空角色和角色组
                Db::table("users_role")->where("users_id=$uid")->delete();
                Db::table("users_role_group")->where("users_id=$uid")->delete();

                //同时增加微信通讯录
                $wx = [];
                $wx['zh'] = htmlspecialchars(trim($data["login_name"]));
                $wx['xm'] = $upData["em_name"];
                $wx['wxh'] = $upData["WeChat"];
                $wx['bm'] = 1;
                $wx['zw'] = db('job')->where('id',$datae_j["job_id"])->value('job_name');
                $wx['sj'] = $upData["mobile"];
                $wx['yx'] = $upData["email"];
                db('cg_wechat')->insert($wx);
            } else {
                //无帐号新增
                $iszhchongfu = Db::table("users")->where("login_name='{$data["login_name"]}'")->find();
                if ($iszhchongfu)
                    return 9;
                //插入帐号表
                $userdata["login_name"] = htmlspecialchars(trim($data["login_name"]));
                $userdata["login_pwd"] = md5(md5(htmlspecialchars(trim($data["login_pwd"]))));
                $userdata["type"] = trim($data["user_type"]);
                $userdata["state"] = trim($data["user_state"]);
                $userdata["is_SFA"] = trim($data["user_is_SFA"]);
                $userdata["power"] = trim($data["user_power"]);
                $userdata["employee_id"] = $data["emid"];
                $userdata["created_on"] = date("Y-m-d H:i:s");
                $res5 = Db::table("users")->insertGetId($userdata);

                $uid = $res5;

                //同时增加微信通讯录
                $wx = [];
                $wx['zh'] = $userdata['login_name'];
                $wx['xm'] = $upData["em_name"];
                $wx['wxh'] = $upData["WeChat"];
                $wx['bm'] = 1;
                $wx['zw'] = db('job')->where('id',$datae_j["job_id"])->value('job_name');
                $wx['sj'] = $upData["mobile"];
                $wx['yx'] = $upData["email"];
                db('cg_wechat')->insert($wx);
            }

            //插入帐号——角色

            $dataur["users_id"] = $uid;
            $dataur["role_id"] = trim($data["role_id"]);
            $res6 = Db::table("users_role")->insert($dataur);


            //插入帐号角色组表
            if (trim($data["roleg_id"])) {
                $dataurg["users_id"] = $uid;
                $dataurg["role_group_id"] = trim($data["roleg_id"]);
                $res7 = Db::table("users_role_group")->insert($dataurg);
            } else {
                $res7 = 1;
            }
        } catch (\Exception $e) {

            Db::rollBack();
            return $e->getMessage();
        }
        if ($res1 && $res2 && $res3 && $res4) {

            Db::commit(); //事物提交
            return 1;
        } else {

            Db::rollBack();
            return 3;//失败
        }
    }

    //修改无帐号
    public function update_employee()
    {
        $request = Request::instance();

        $data = $request->post();//接收数据
        //接收和处理数据
        $upData["id"] = $data["emid"];
        $upData["em_no"] = htmlspecialchars(trim($data["em_no"]));
        $upData["em_name"] = htmlspecialchars(trim($data["em_name"]));
        $upData["state"] = trim($data["state"]);
        $upData["mobile"] = htmlspecialchars(trim($data["mobile"]));
        $upData["WeChat"] = htmlspecialchars(trim($data["wechart"]));
        $upData["email"] = htmlspecialchars(trim($data["email"]));
        $upData["idcard"] = htmlspecialchars(trim($data["idcard"]));
        $upData["gender"] = trim($data["gender"]);
        $upData["modifiled_on"] = date("Y-m-d H:i:s");
        if ($data["entry"]) {
            $upData["entry"] = trim($data["entry"]);
        }
        Db::startTrans(); //开启事物
        try {
            $res1 = Db::table("employee")->update($upData);
            //部门处理
            //
            Db::table("department_employee")->where("employee_id={$data["emid"]}")->delete();
            $datae_d[0]["employee_id"] = $data["emid"];
            $datae_d[0]["department_id"] = htmlspecialchars(trim($data["de_id"]));
            $datae_d[0]["index"] = 1;
            //其他部门
            $odearr = trim($data["otherdepart"]);
            if ($odearr) {
                $odearr = explode(",", $odearr);
                for ($i = 0; $i < count($odearr); $i++) {
                    $datae_d[$i + 1]["employee_id"] = $data["emid"];
                    $datae_d[$i + 1]["department_id"] = $odearr[$i];
                    $datae_d[$i + 1]["index"] = 2;
                }
            }
            $res2 = Db::table("department_employee")->insertAll($datae_d);
            //岗位处理
            Db::table("job_employee")->where("employee_id={$data["emid"]}")->delete();
            $datae_j["employee_id"] = $data["emid"];
            $datae_j["job_id"] = htmlspecialchars(trim($data["job_id"]));

            $res3 = Db::table("job_employee")->insert($datae_j);
            //判断是否需要修改部门的第一负责人
            $depa = Db::table("department")->where("id={$data["de_id"]}")->find();
            $principalid = $depa["principal"];
            $res4 = "";
            if ($data["is_main"] == 1) {
                $dechage["principal"] = $data["emid"];
                $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                $res4 = Db::table("department")->update($dechage);
            } else {
                if ($principalid == $data["emid"]) {
                    $dechage["principal"] = null;
                    $dechage["modifiled_on"] = date("Y-m-d H:i:s");
                    $dechage["id"] = htmlspecialchars(trim($data["de_id"]));
                    $res4 = Db::table("department")->update($dechage);
                } else {
                    $res4 = 1;
                }
            }
        } catch (\Exception $e) {

            Db::rollBack();
            return 2;
        }
        if ($res1 && $res2 && $res3 && $res4) {

            Db::commit(); //事物提交
            return 1;
        } else {

            Db::rollBack();
            return 3;//失败
        }
    }

    public function get_role_tree($roleid = 0)
    {
        $role_arr = Db::table("role")->where("is_actived=1 and is_deleted=0")->select();
        $result = [];
        for ($i = 0; $i < count($role_arr); $i++) {
            $result[$i]["id"] = $role_arr[$i]["id"];
            $result[$i]["pId"] = $role_arr[$i]["parent_id"];
            $result[$i]["name"] = $role_arr[$i]["role_name"];
            if ($result[$i]["id"] == $roleid) {
                $result[$i]["chkDisabled"] = true;
            }
        }


        return json_encode($result);
    }


    public function get_prole_tree($roleid = 2, $proleid = 1)
    {
        $role_arr = Db::table("role")->where("is_actived=1 and is_deleted=0")->select();
        $result = [];
        for ($i = 0; $i < count($role_arr); $i++) {
            $result[$i]["id"] = $role_arr[$i]["id"];
            $result[$i]["pId"] = $role_arr[$i]["parent_id"];
            $result[$i]["name"] = $role_arr[$i]["role_name"];

            if ($role_arr[$i]["path"]) {
                $arr = explode('[', $role_arr[$i]["path"]);
                $str = implode('', $arr);
                $notp = explode("]", $str);
                //return $arr;
                // print_r($notp);//exit;
            } else {
                $notp = [];
            }
            if ($result[$i]["id"] == $roleid || in_array($roleid, $notp)) {
                $result[$i]["chkDisabled"] = true;
            }


            if ($result[$i]["id"] == $proleid) {
                $result[$i]["checked"] = true;
            }
            $result[$i]["open"] = true;
        }
        return json_encode($result);
    }

    //查询角色明细，包括上级详情和所属人员
    public function getrole_de($roleid)
    {
        $data = [];
        $nowid = Db::table("role")->where("id=$roleid")->find();
        $pid = $nowid["parent_id"];
        if ($pid) {
            $data["role"] = Db::table("role")->where("id={$pid}")->select();
        } else {
            $data["role"] = [];
        }
        $data["user"] = Db::table("role")->alias("r")
            ->join("users_role ur", "ur.role_id=r.id")
            ->join("users u", "ur.users_id=u.id")
            ->join("employee e", "u.employee_id=e.id")
            ->where("r.id={$roleid}")->limit(0, 10)
            ->field("e.em_name")->select();

        $puser = Db::table("role")->alias("r")
            ->join("role pr", "r.parent_id=pr.id")
            ->join("users_role ur", "ur.role_id=pr.id")
            ->join("users u", "ur.users_id=u.id")
            ->join("employee e", "u.employee_id=e.id")
            ->where("r.id={$roleid}")->limit(0, 10)
            ->field("e.em_name,e.id")->select();
        $pguser = [];
        $pguser = Db::table("role")->alias("r")
            ->join("role pr", "r.parent_id=pr.id")
            ->join("role_edit re", "pr.id=re.role_id")
            ->join("role_group rg", "re.group_id=rg.id")
            ->join("users_role_group urg", "urg.role_group_id=rg.id")
            ->join("users u", "urg.users_id=u.id")
            ->join("employee e", "u.employee_id=e.id")
            ->where("r.id={$roleid}")->limit(0, 10)
            ->field("e.em_name,e.id")
            ->select();
        $all_puser = [];
        $eids = [];
        $renshu = 0;
        for ($i = 0; $i < count($puser); $i++) {
            $all_puser[] = $puser[$i];
            $eids[] = $puser[$i]["id"];
            $renshu++;
        }
        if ($renshu < 10) {
            for ($i = 0; $i < count($pguser); $i++) {
                if (!in_array($pguser[$i]["id"], $eids)) {
                    $all_puser[] = $pguser[$j];
                    $eids[] = $pguser[$j]["id"];
                    $renshu++;
                    if ($renshu == 10)
                        break;
                }
            }
        }

        $data["puser"] = $all_puser;
        return json_encode($data);
    }

    //查询角色上级
    public function checkrole_p($roleid)
    {
        //return $roleid;
        $data = [];
        $data = Db::table("role")->alias("r")->join("role rp", "r.parent_id=rp.id", "LEFT")->where(["r.id" => $roleid])
            ->field("r.id,r.role_name,r.parent_id as pid,rp.role_name as pname,r.remark")
            ->select();
        return json_encode($data);
    }

    //
    public function getallrole()
    {
        $request = Request::instance();
        $data = $request->post();

        $rids = $data["rids"];
        //echo $deids;exit;
        $ridsarr = [];
        if ($rids) {
            $ridsarr = explode(',', $rids);
        }
        $departs = Db::table("role")->where(["is_actived" => 1, "is_deleted" => 0])
            ->field("id,parent_id as pId,role_name as name")->select();
        $result = [];
        for ($i = 0; $i < count($departs); $i++) {
            $result[$i]["id"] = $departs[$i]["id"];
            $result[$i]["pId"] = $departs[$i]["pId"];
            $result[$i]["name"] = $departs[$i]["name"];

            if (in_array($result[$i]["id"], $ridsarr)) {
                $result[$i]["checked"] = true;
            }
            $result[$i]["open"] = true;
        }


        return json_encode($result);
    }

    //获取角色组
    public function get_roleg_tree()
    {
        $arr = Db::table("role_group")->where("is_deleted=0 and is_actived=1")->select();
        $result = [];
        for ($i = 0; $i < count($arr); $i++) {
            $result[$i]["id"] = $arr[$i]["id"];

            $result[$i]["name"] = $arr[$i]["group_name"];


        }


        return json_encode($result);
    }

    //查询分组下的所有角色
    public function getgcr($rgid)
    {
        $arr = Db::table("role_edit")->alias("re")
            ->join("role r", "re.role_id=r.id", "LEFT")
            ->where("re.group_id={$rgid} and r.is_deleted=0 and r.is_actived=1")
            ->field("r.role_name,r.id")
            ->select();
        $result = '';
        for ($i = 0; $i < count($arr); $i++) {
            $result.= ($arr[$i]["role_name"].'<a onclick="powerlist('.$arr[$i]["id"].')">设置web端权限</a><br/>');
        }
        return $result;

    }

    public function getrolegroup_de($rgid)
    {

        $arr = Db::table("role_group")->alias("rg")
            ->join("role_edit e", "rg.id=e.group_id", "LEFT")
            ->join("role r", "e.role_id=r.id", "LEFT")
            ->where("e.group_id={$rgid} and r.is_deleted=0 and r.is_actived=1")
            ->field("rg.id,rg.group_name,r.role_name,r.id as rid,rg.remark")
            ->select();
        return json_encode($arr);
    }

    //保存或新增角色组
    public function role_group_edit()
    {
        $request = Request::instance();
        $data = $request->post();

        $newdata["group_name"] = htmlspecialchars(trim($data["group_name"]));
        $newdata["remark"] = htmlspecialchars(trim($data["remark"]));
        $id = trim($data["id"]);
        if (!$newdata["group_name"])
            return 4;//组名空
        if (!$data["rids"])
            return 5;//无角色
        if ($id) {
            //修改
            $ischongfu = Db::table("role_group")->where("group_name='{$newdata["group_name"]}' and id<>$id")->count();
            if ($ischongfu) {
                return 3;
            }
            $newdata["modifiled_on"] = date("Y-m-d H:i:s");
            $newdata["id"] = $id;
            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("role_group")->update($newdata);
                Db::table("role_edit")->where("group_id=$id")->delete();
                $arr = explode(',', $data["rids"]);
                $datare = [];
                for ($i = 0; $i < count($arr); $i++) {
                    $datare[$i]["group_id"] = $id;
                    $datare[$i]["role_id"] = $arr[$i];
                }
                $res2 = Db::table("role_edit")->insertAll($datare);
            } catch (\Exception $e) {

                Db::rollBack();
                return 2;
            }
            if ($res1 && $res2) {
                Db::commit();
                return 1;
            } else {
                Db::rollBack();
                return 2;
            }

        } else {
            //添加
            $newdata["created_on"] = date("Y-m-d H:i:s");

            $ischongfu = Db::table("role_group")->where("group_name='{$newdata["group_name"]}'")->count();
            if ($ischongfu) {
                return 3;
            }
            Db::startTrans(); //开启事物
            try {
                $res1 = Db::table("role_group")->insertGetId($newdata);
                $arr = explode(',', $data["rids"]);
                $datare = [];
                for ($i = 0; $i < count($arr); $i++) {
                    $datare[$i]["group_id"] = $res1;
                    $datare[$i]["role_id"] = $arr[$i];
                }
                //return json_encode($datare);
                $res2 = Db::table("role_edit")->insertAll($datare);
            } catch (\Exception $e) {

                Db::rollBack();
                return 2;
            }
            if ($res1 & $res2) {
                Db::commit();
                return 1;
            } else {
                Db::rollBack();
                return 2;
            }
        }
    }

    //重置密码
    public function resetpwd($id)
    {
        if ($id) {
            Db::startTrans(); //开启事物
            try {
                $data["login_pwd"] = md5(md5(111111));
                $data["id"] = $id;
                $res1 = Db::table("users")->update($data);
            } catch (\Exception $e) {

                Db::rollBack();
                return 2;
            }
            if ($res1) {
                Db::commit();
                return 1;
            } else {
                Db::rollBack();
                return 2;
            }
        } else {
            return 0;
        }
    }
}